package com.wtwd.campus.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.entity.SysOrg;
import com.wtwd.campus.entity.SysUser;
import com.wtwd.campus.model.vo.*;
import com.wtwd.campus.service.SysOrgService;
import com.wtwd.campus.service.SysUserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zdl
 * @since 2021-06-08
 */
@Api(tags = "组织管理")
@RestController
@RequestMapping("/sys-org")
public class SysOrgController {
    @Resource
    private SysOrgService sysOrgService;

    @Resource
    private SysUserService sysUserService;
    private static final Logger logger = LoggerFactory.getLogger(SysOrgController.class);


    @ApiOperation(value = "查询组织分页数据", notes = "当参数包含组织ID时,获取该组织下级组织")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "orgName", value = "组织名称", dataType = "String")
            , @ApiImplicitParam(name = "orgId", value = "组织ID", dataTypeClass = Integer.class)
    })
    @GetMapping("/page")
    public ResultVO<PageDataVO<SysOrgVO>> queryPage(@RequestParam(defaultValue = "1") Integer pageNo
            , @RequestParam(defaultValue = "10") Integer pageSize, String orgName, Integer orgId) {
        logger.info("sys-org-queryPage : param " + pageNo,pageSize,orgName,orgId);
        Page<SysOrg> page = new Page<>(pageNo, pageSize);
        SysOrg sysOrg = new SysOrg();
        String orgCode = sysUserService.getCurrentLoginUser().getOrgCode();
        sysOrg.setOrgType("1");
        sysOrg.setOrgCode(orgCode);
        if (StringUtils.isNotBlank(orgName)) {
            sysOrg.setOrgName(orgName);
        }
        if (orgId != null) {
            sysOrg.setId(orgId);
        }
        IPage<SysOrgVO> data = sysOrgService.queryPage(page, sysOrg);
        return ResultVO.ok(data);
    }

    /**
     * 1.添加组织信息
     * 2.添加组织权限
     *
     * @param param
     * @return
     */
    @ApiOperation("添加组织信息")
    @DynamicParameters(name = "addOrgJson", properties = {
            @DynamicParameter(name = "orgName", value = "组织名称", required = true, dataTypeClass = String.class)
            , @DynamicParameter(name = "pid", value = "父组织ID", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "province", value = "省", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "city", value = "市", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "permissions", value = "组织权限", dataTypeClass = String.class, required = true, example = "51,52")
            , @DynamicParameter(name = "renewDay", value = "续费时间天数", dataTypeClass = Integer.class)
    })
    @Transactional
    @PostMapping("/orgInfo")
    public ResultVO add(@RequestBody JSONObject param) {
        logger.info("sys-org-add : param " + param);

        //如果是总部。选传入的天数转时间戳 + 当前时间戳；  非总部，找到当前组织的过期时间设置进去
        Long expireTime = 0L;
        if (param.containsKey("renewDay")) {
            Integer renewDay = param.getInteger("renewDay");
            expireTime = System.currentTimeMillis() + renewDay * 24 * 60 * 60 * 1000L;
        } else {
            String orgCode = sysUserService.getCurrentLoginUser().getOrgCode();
            SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(orgCode);
            expireTime = sysOrg.getExpiresTime();
        }
        SysOrg sysOrg = JSONObject.toJavaObject(param, SysOrg.class);
        sysOrg.setExpiresTime(expireTime);
        ResultVO result = sysOrgService.save(sysOrg);
        String permissions = param.getString("permissions");
        if (StringUtils.isNotBlank(permissions)) {
            sysOrgService.saveOrgPermissionBatch(sysOrg.getId(),sysOrg.getOrgCode(), permissions);
        }
        return result;
    }

    @ApiOperation("更新组织信息")
    @DynamicParameters(name = "updateOrgJson", properties = {
            @DynamicParameter(name = "id", value = "组织id", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "orgName", value = "组织名称", dataTypeClass = String.class)
            , @DynamicParameter(name = "province", value = "省", dataTypeClass = String.class)
            , @DynamicParameter(name = "city", value = "市", dataTypeClass = String.class)
            , @DynamicParameter(name = "permissions", value = "组织权限", dataTypeClass = String.class, example = "51,52")
            , @DynamicParameter(name = "renewDay", value = "续费时间天数", dataTypeClass = Integer.class)
    })
    @Transactional
    @PutMapping("/orgInfo")
    public ResultVO update(@RequestBody JSONObject param) {
        logger.info("sys-org-update : param " + param);
        Long expireTime = 0L;
        if (param.containsKey("renewDay")) {
            Integer renewDay = param.getInteger("renewDay");
            expireTime = System.currentTimeMillis() + renewDay * 24 * 60 * 60 * 1000L;
        }
        SysOrg sysOrg = JSONObject.toJavaObject(param, SysOrg.class);
        ResultVO respentity = sysOrgService.updateById(sysOrg);
        if (expireTime != 0) {
            // 修改客户及其下级的过期时间
            sysOrgService.renewSysOrgAndSub(param.getInteger("id"), expireTime);
        }

        String permissions = param.getString("permissions");
        if (StringUtils.isNotBlank(permissions)) {
            sysOrgService.saveOrgPermissionBatch(sysOrg.getId(), sysOrgService.getOrgCodeById(sysOrg.getId()), permissions);
        }
        return respentity;
    }

    @ApiOperation("删除组织信息")
    @ApiImplicitParam(name = "id", value = "组织id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @ApiResponses({
            @ApiResponse(code = 2001, message = "该组织存在下级,无法删除")
            , @ApiResponse(code = 2002, message = "该组织存在角色")
            , @ApiResponse(code = 2003, message = "该组织存在学校")
    })
    @DeleteMapping("/orgInfo/{id}")
    public ResultVO delete(@PathVariable Integer id) {
        logger.info("sys-org-delete : param " + id);
        return sysOrgService.deleteById(id);
    }

    @ApiOperation("获取组织树")
    @ApiImplicitParam(name = "showOrgType", value = "显示组织类型", required = true, dataTypeClass = Integer.class, paramType = "path", example = "1-显示组织,2-包含学校,3-包含年级,4-包含班级")
    @GetMapping("/orgTree/{showOrgType}")
    public ResultVO<List<OrgTreeVO>> getOrgTree(@PathVariable Integer showOrgType) {
        logger.info("sys-org-getOrgTree : param " + showOrgType);
        SysUser currentUser = sysUserService.getCurrentLoginUser();
        return sysOrgService.getOrgTreeByOrgCode(currentUser.getOrgCode(), showOrgType);
    }


    @ApiOperation("获取组织权限菜单树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "组织id", required = true, dataTypeClass = Integer.class, paramType = "path"),
            @ApiImplicitParam(name = "type", value = "0 中文 1英文", required = true, dataTypeClass = Integer.class, paramType = "type")
       }
    )
    @GetMapping("/permissionMenuTree/{orgId}")
    public ResultVO<List<PermissionTreeVO>> getPermissionMenuTree(@PathVariable Integer orgId, @RequestParam(required = false) Integer type) {
        logger.info("sys-org-getPermissionMenuTree : param " + orgId,+type);
        return sysOrgService.getOrgPermissionTreeByOrgId(orgId, type);
    }

    @ApiOperation("获取组织权限")
    @ApiImplicitParam(name = "orgId", value = "组织Id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @GetMapping("/orgPermission/{orgId}")
    public ResultVO<List<Integer>> getOrgPermission(@PathVariable Integer orgId) {
        logger.info("sys-org-getOrgPermission : param " + orgId);
        return ResultVO.ok(sysOrgService.getOrgPermissionIdsByOrgId(orgId));
    }
}

